﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Nav3;
using Nav3.EventArgs;
using System.Configuration;
using BAL.EstRec.SYNC;
using MasterDetailEx.Notify;
using System.Threading;
using System.Windows.Threading;
using FileOps;
using BAL.EstRec;
using BAL.EstRec.SQL;
using System.Diagnostics;
using BAL.EstRec.AUTH;
using System.Data;
using System.Security.Principal;
using BAL.EstRec.Common;


namespace MasterDetailEx
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window , ISyncEventImp,IUIRefresher
    {
        CapturaHq hq;
        CapturaFDV fdv;
        ConsolidacionHQ chq;
        CapturaRHQ crhq;
        string currentUnidVersion;
        string currentPositionCode;
        TagCreateControl currentTagControl;

        Control currentControl;
        public PopupNotify pop;
        AppConfs Configs;

        DispatcherTimer dTimerClock;
        public DispatcherTimer DTimerClock
        {
            get { return dTimerClock; }
            set { dTimerClock = value; }
        }

        DispatcherTimer dTimerClockPublicar;
        public DispatcherTimer DTimerClockPublicar
        {
            get { return DTimerClockPublicar; }
            set { DTimerClockPublicar = value; }
        }

        DispatcherTimer dTimerClock1;
        public DispatcherTimer DTimerClock1
        {
            get { return dTimerClock1; }
            set { dTimerClock1 = value; }
        }

        public string ActualUser { get; set; }
        public bool isHQ { get; set; }
        public bool isFDV { get; set; }
        public bool isAdmin { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            try
            {
                Configs = new AppConfs();
                //PublishSharePoint.GetPublicar(@"http://workpoint.app.pmi", @"blogs/CFET/Registros", @"C:\Users\Administrator\Desktop\Prueba\prueba.txt", "prueba.txt");
                //pop = new PopupNotify(ad);
                #region EJECUCIÓN DE SCRIPTS SQL
                try
                {
                    ExecSQL exS = new ExecSQL();
                    exS.CnnString = Configs.cnf.cnnString.ToString();
                    exS.ScriptsFailurePath = Configs.cnf.scriptsFailurePath.ToString();
                    exS.ScriptsSuccessPath = Configs.cnf.scriptsSuccessPath.ToString();
                    exS.ScriptsPath = Configs.cnf.scriptsPath.ToString();
                    exS.ExecScripts();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error SQL: " + e.Message);
                }
                #endregion

                #region search for new app updates
                dTimerClock = new DispatcherTimer();
                dTimerClock.Tick += new EventHandler(dTimerClock_Tick);
                dTimerClock.Interval = new TimeSpan(0, 0, 1);
                dTimerClock.Start();

                dTimerClock1 = new DispatcherTimer();
                dTimerClock1.Tick += new EventHandler(dTimerClockStatusConn_Tick);
                dTimerClock1.Interval = new TimeSpan(0, 0, 1);
                dTimerClock1.Start();

                #endregion

                //Aquí se inicializa currentControl por default para fines de prueba
                //currentPositionCode = "830702";        

                ActualUser = Auth.ActualUserType();

                

                //MessageBox.Show(ActualUser);

                if (ActualUser.Equals("FDV"))
                {
                    this.currentPositionCode = Auth.GetTerritorio();
                    //fdv.currentPositionCode = this.currentPositionCode;

                    this.isFDV = true;
                    this.isHQ = false;
                    this.isAdmin = false;

                    lblCargaHQ.Visibility = System.Windows.Visibility.Collapsed;
                    lblConsolidacionHQ.Visibility = System.Windows.Visibility.Collapsed;
                    lblCapturaFDV.Visibility = System.Windows.Visibility.Visible;
                    lblCargaRHQ.Visibility = System.Windows.Visibility.Visible;

                    this.fdv = new CapturaFDV();
                    this.crhq = new CapturaRHQ();
                    this.fdv.currentPositionCode = this.currentPositionCode;
                    fdv.LlenarCombos();
                    //this.currentControl = crhq;

                    

                    MouseButtonEventArgs e = new MouseButtonEventArgs(Mouse.PrimaryDevice,0,MouseButton.Left) { 
                        RoutedEvent = Control.MouseUpEvent 
                    };
                    this.lblCargaRHQ.RaiseEvent(e);

                    /*
                    this.removeContentControl();
                    this.contentControls.Children.Add(crhq);
                    this.currentControl = crhq;
                    this.setSelectedLabel(lblCargaRHQ);
                     * */
                    
                }
                else if (ActualUser.Equals("HQ"))
                {

                    this.isFDV = false;
                    this.isHQ = true;
                    this.isAdmin = false;

                    lblCargaHQ.Visibility = System.Windows.Visibility.Visible;
                    lblConsolidacionHQ.Visibility = System.Windows.Visibility.Visible;
                    lblCapturaFDV.Visibility = System.Windows.Visibility.Collapsed;
                    lblCargaRHQ.Visibility = System.Windows.Visibility.Collapsed;

                    this.hq = new CapturaHq();
                    this.chq = new ConsolidacionHQ();

                    //Cargar la pestaña
                    this.nav.init(this.isFDV, this.currentPositionCode);
                    MouseButtonEventArgs e = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
                    {
                        RoutedEvent = Control.MouseUpEvent
                    };
                    this.lblCargaHQ.RaiseEvent(e);
                }
                else if (ActualUser.Equals("Admin"))
                {
                    currentPositionCode = Auth.GetTerritorio();
                    //fdv.currentPositionCode = this.currentPositionCode;

                    this.isFDV = false;
                    this.isHQ = false;
                    this.isAdmin = true;

                    lblCargaHQ.Visibility = System.Windows.Visibility.Visible;
                    lblConsolidacionHQ.Visibility = System.Windows.Visibility.Visible;
                    lblCapturaFDV.Visibility = System.Windows.Visibility.Visible;
                    lblCargaRHQ.Visibility = System.Windows.Visibility.Visible;

                    this.fdv = new CapturaFDV();
                    this.crhq = new CapturaRHQ();
                    this.hq = new CapturaHq();
                    this.chq = new ConsolidacionHQ();

                    //Cargar la pestaña
                    this.nav.init(this.isFDV, this.currentPositionCode);
                    MouseButtonEventArgs e = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
                    {
                        RoutedEvent = Control.MouseUpEvent
                    };
                    this.lblCargaHQ.RaiseEvent(e);
                }
                else
                {
                    lblCargaHQ.Visibility = System.Windows.Visibility.Hidden;
                    lblConsolidacionHQ.Visibility = System.Windows.Visibility.Hidden;
                    lblCapturaFDV.Visibility = System.Windows.Visibility.Hidden;
                    lblCargaRHQ.Visibility = System.Windows.Visibility.Hidden;
                    MessageBox.Show("No tiene permiso para acceder a la aplicación. \nValide que su usuario pertenezca al grupo correcto.", "Acceso denegado", MessageBoxButton.OK, MessageBoxImage.Stop);
                    this.Close();
                }

                //this.nav.selectFirstItem();
                //Inicializar NavControl


                #region Sincronización de catálogos
                try
                {
                    //DispatcherOperation dop = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                    //new Action(() =>
                    //{
                    //    //AutSyncCat.start(this, Configs);
                    //}));
                    SyncCatProcess();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error en la sincronización de catálogos: " + ex.Message);
                }
                #endregion

            
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message +". InnerEx: "+ ex.InnerException);
            }
        }
       
        private void UserControl1_NewItem(object sender, RoutedEventArgs e)
        {
            this.disableMouseUI();

            try
            {
                //Guardar la versión actual
                this.currentUnidVersion = ((SelectItemEventArgs)e).unid.ToString();
                this.currentTagControl = this.nav.getSelectedItem();

                if (this.currentControl!=null)
                {
                    if (this.currentControl.GetType() == typeof(Nav3.CapturaHq))
                    {
                        if (hq != null)
                        {
                            hq.setUnidVersion(this.currentUnidVersion,this.currentTagControl);
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.CapturaFDV))
                    {
                        if (fdv != null)
                        {
                            fdv.setVersion(this.currentUnidVersion, this.currentTagControl);
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.ConsolidacionHQ))
                    {
                        if (this.chq != null)
                        {
                            this.chq.loadData(Convert.ToInt64(this.currentUnidVersion));
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.CapturaRHQ))
                    {
                        if (this.crhq != null)
                        {
                            this.loadCargaRhq();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if(ex.Message.Contains("Versión sin datos"))
                    MessageBox.Show(ex.Message, "Versión sin Datos", MessageBoxButton.OK, MessageBoxImage.Information);
                else
                     MessageBox.Show("Ocurrió un error al cargar el control. \nValide que cuenta con los permisos suficientes para usar la aplicación.\nDetalle : " + ex.Message + "\nInner: " + ex.InnerException, "Carga selected item", MessageBoxButton.OK, MessageBoxImage.Stop);
            }

            this.enableMouseUI();
        }

        private void lblCargaHQ_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.disableMouseUI();

            try
            {
                if (currentControl != null)
                {
                    InterfazControl ic = currentControl as InterfazControl;
                    ISave save = currentControl as ISave;

                    if (ic.IsModified)
                    {
                        if (MessageBox.Show("¿Desea guardar los cambios antes de salir?", "Mensaje del Sistema", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {

                            //llamamos a la funcion que actualiza o inserta a la base
                            save.save();
                            ic.IsModified = false;
                        }
                        else
                        {
                            save.loadData();
                            ic.IsModified = false;
                        }
                    }
                }

                this.removeContentControl();
                this.contentControls.Children.Add(hq);
                this.currentControl = hq;
                this.setSelectedLabel((Label)sender);

                this.nav.init(false, this.currentPositionCode);
                this.nav.loadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ocurrió un error al cargar la información. \nValide que la base de datos exista y que el servicio de SQL se encuentre activo.\nDetalle : " + ex.Message + "\nInner: " + ex.InnerException, "Carga HQ", MessageBoxButton.OK, MessageBoxImage.Stop);
            }

            this.enableMouseUI();
        }

        private void lblCapturaFDV_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.disableMouseUI();
            try
            {
                if (currentControl != null)
                {
                    InterfazControl ic = currentControl as InterfazControl;
                    ISave save = currentControl as ISave;
                    if (ic.IsModified)
                    {
                        if (MessageBox.Show("¿Desea guardar los cambios antes de salir?", "Mensaje del Sistema", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            save.save();
                            ic.IsModified = false;
                        }
                        else
                        {
                            save.loadData();
                            ic.IsModified = false;
                        }
                    }
                }

                this.removeContentControl();
                this.contentControls.Children.Add(fdv);
                this.currentControl = fdv;
                fdv.currentPositionCode = this.currentPositionCode;
                this.setSelectedLabel((Label)sender);

                //Carga nav solo si no estaba en una pestaña que perteneciera a FDV
                this.nav.init(true, this.currentPositionCode);
                this.nav.loadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: "+ex.Message + ". InnerEx: " + ex.InnerException);
            }

            this.enableMouseUI();
        }

        private void disableMouseUI()
        {
            this.IsHitTestVisible = false;
            Mouse.OverrideCursor = Cursors.Wait;
        }

        public void enableMouseUI()
        {
            this.IsHitTestVisible = true;
            Mouse.OverrideCursor = Cursors.Arrow;
        }

        private void lblCargaRHQ_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.disableMouseUI();

            this.crhq.VerticalAlignment = VerticalAlignment.Top;
            
            this.currentControl = this.crhq;

            this.removeContentControl();
            this.setSelectedLabel(this.lblCargaRHQ);
            this.contentControls.Children.Add(this.crhq);
            //(this.contentControls.Children[0] as UserControl).Height = this.brd.ActualHeight;
            this.nav.init(true, this.currentPositionCode);
            this.nav.loadData();

            this.enableMouseUI();
        }

        private void loadCargaRhq()
        {
            if (currentControl != null)
            {
                InterfazControl ic = currentControl as InterfazControl;
                ISave save = currentControl as ISave;
                if (ic.IsModified)
                {
                    if (MessageBox.Show("¿Desea guardar los cambios antes de salir?", "Mensaje del Sistema", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        save.save();
                        ic.IsModified = false;
                    }
                    else
                    {
                        save.loadData();
                        ic.IsModified = false;
                    }
                }

            }
            
            this.crhq = new CapturaRHQ();
            this.crhq.setUnidVersion(Convert.ToInt64(this.currentUnidVersion));
            this.crhq.setTerritorio(this.currentPositionCode);
            this.crhq.loadControl();
            this.currentControl = this.crhq;

                this.removeContentControl();
                this.setSelectedLabel(this.lblCargaRHQ);
                this.contentControls.Children.Add(this.crhq);
        }

        private void lblConsolidacionHQ_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.disableMouseUI();

            if (currentControl != null)
            {
                InterfazControl ic = currentControl as InterfazControl;
                ISave save = currentControl as ISave;

                if (ic.IsModified)
                {
                    if (MessageBox.Show("¿Desea guardar los cambios antes de salir?", "Mensaje del Sistema", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        save.save();
                        ic.IsModified = false;

                    }
                    else
                    {
                        save.loadData();
                        ic.IsModified = false;
                    }
                }
            }


            this.removeContentControl();
            this.contentControls.Children.Add(chq);
            this.currentControl = chq;
            
            this.setSelectedLabel((Label)sender);

            this.nav.init(false, this.currentPositionCode);
            this.nav.loadData();

            this.enableMouseUI();
        }

        private void removeContentControl()
        {
            if (this.contentControls.Children.Count > 0)
            {
                this.contentControls.Children.RemoveAt(0);
            }
        }
        private void setSelectedLabel(Label selected)
        {            
            foreach (var x in this.spLabelCont.Children)
            {            
                ((Label)(x)).Background = Brushes.Transparent;
                ((Label)(x)).Foreground = Brushes.Black;
                selected.Foreground = Brushes.White;
            }


            selected.Background = (Brush)(new BrushConverter()).ConvertFromString("#00BFFF"); // Brushes.Aqua;
            selected.Foreground = Brushes.White;
        }

        //--------------------------------------------------------------
        void dTimerClock_Tick(object sender, EventArgs e)
        {
            TimeSpan tsTimer = new TimeSpan(int.Parse(Configs.cnf.timeSpn_h), int.Parse(Configs.cnf.timeSpn_m), int.Parse(Configs.cnf.timeSpn_s));
            ((DispatcherTimer)sender).Interval = tsTimer;

            //new System.Threading.Thread(delegate()
            //{
                Updates.start(this,Configs);
                BAL.EstRec.SyncCierre.ThreadSyncCierre.start(this);
            //}).Start();

           
        }

        void dTimerClockStatusConn_Tick(object sender, EventArgs e)
        {
            TimeSpan ts;
            try
            {
                MainWindow mw = (MainWindow)App.Current.MainWindow;
                if (mw == null)
                    EndAppProcess(Configs.cnf.appName);
                ts = new TimeSpan(0, 0, 20);
                ((DispatcherTimer)sender).Interval = ts;
            }
            catch (Exception)
            {
            }
        }


        private void obj_SyncEvent(object sender, SyncEventArgs e)
        {

            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.StatSync.Estatus, e.StatSync.Error);
            string SyncMsg = "+ " + e.StatSync.Estatus;

            DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                    PopupNotify.start(mw, SyncMsg);

                }));
        }

        private void btn_sync_Click(object sender, RoutedEventArgs e)
        {
            //Sync objSync = new Sync(clientFileFolder, serverFileFolder, zipPath, tmpCatPath);
            //objSync.SyncEventH += new BAL.EstRec.SYNC.EventHandler<SyncEventArgs>(obj_SyncEvent);
            //bool a = objSync.SyncData();

            SyncProcess();

        }

        public void SyncProcess()
        {
            FolderSync fs = new FolderSync();
            fs.CatZipPath = Configs.cnf.svrCatZipPath.ToString();
            fs.ClntCatZipPath = Configs.cnf.clntCatZipPath.ToString();
            fs.TmpCatPath = Configs.cnf.tmpCatPath.ToString();
            fs.ClientDataPath = Configs.cnf.clientDataPath.ToString();
            fs.ServerDataPath = Configs.cnf.serverDataFolder.ToString();
            fs.DataFilesFolder = Configs.cnf.dataFilesFolder.ToString();

            fs.FilesProcessedPath = Configs.cnf.ProcessedFilesSync;

            //fs.FileDownloadedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_fileDownloaded);
            //fs.FileErrorEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileErrorEvent);
            //fs.FileUnzippedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileUnzippedEvent);
            //fs.FileUploadedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileUploadedEvent);
            //fs.FileEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileEvent);
            //fs.SyncCompletedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_SyncCompletedEvent);

            //fs.SyncCat();

            //fs.loadData();
            if (this.ActualUser.ToUpper() =="HQ")
                SyncThread.start(fs, (ISyncEventImp)this, true);
            else
                SyncThread.start(fs, (ISyncEventImp)this, false);
        }

        /*
        private void btn_data_Click(object sender, RoutedEventArgs e)
        {
            string clientFileFolder = ConfigurationManager.AppSettings["clientFileFolder"].ToString();
            string serverFileFolder = ConfigurationManager.AppSettings["serverFileFolder"].ToString();

            string svrCatZipPath = System.Configuration.ConfigurationManager.AppSettings["zipFilePathSvr"].ToString();
            string clntCatZipPath = System.Configuration.ConfigurationManager.AppSettings["zipFilePathClnt"].ToString();
            string tmpCatPath = System.Configuration.ConfigurationManager.AppSettings["tmpDataFolder"].ToString();

            string clientDataPath = System.Configuration.ConfigurationManager.AppSettings["clientDataFolder"].ToString();
            string serverDataFolder = System.Configuration.ConfigurationManager.AppSettings["serverDataFolder"].ToString();
            string dataFilesFolder = System.Configuration.ConfigurationManager.AppSettings["dataFilesFolder"].ToString();


            FolderSync fs = new FolderSync();
            fs.CatZipPath = svrCatZipPath;
            fs.ClntCatZipPath = clntCatZipPath;
            fs.TmpCatPath = tmpCatPath;
            fs.ClientDataPath = clientDataPath;
            fs.ServerDataPath = serverDataFolder;
            fs.DataFilesFolder = dataFilesFolder;

            fs.FileDownloadedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_fileDownloaded);
            fs.FileErrorEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileErrorEvent);
            fs.FileUnzippedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileUnzippedEvent);
            fs.FileUploadedEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileUploadedEvent);
            fs.FileEvent += new FileOps.EventHandler<FolderSyncEventArgs>(fs_FileEvent);
            fs.loadData();
        }//
        */

        private void btn_data_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void btn_sync_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }//

        public void refreshUi()
        {
            this.nav.loadData();
        }

        #region sync eventHandlers

        public void fs_SyncCompletedEvent(object sender, FolderSyncEventArgs e)
        {
            
            this.refreshUi();

        }

        public void fs_FileEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                    PopupNotify.start(mw, SyncMsg);

                }));
        }

        public void fs_FileErrorEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                    PopupNotify.start(mw, SyncMsg);

                }));
        }

        public void fs_fileDownloaded(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                //Sync.upsertCatFileStatus(0, 0, fs.FileName, true);
                Sync.upsertCatZipStatus(0, fs.FileName, true, false);

                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(() =>
            {
                //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                PopupNotify.start(mw, SyncMsg);

            }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message); 
                
            }
            
        }//

        public void fs_FileUnzippedEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                if (e.FileSync.isCat)
                    Sync.upsertCatZipStatus(0, e.FileSync.FileName, true, e.FileSync.Descomprimido);
                if (e.FileSync.isData)
                    Sync.upsertControlTable(0, fs.FileName, "Data", true, false, false);


                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(() =>
            {
                PopupNotify.start(mw, SyncMsg);

            }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message);
            }
        }

        public void fs_FileUploadedEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                if (e.FileSync.isCat)
                    Sync.upsertCatFileStatus(e.FileSync.IdCat, e.FileSync.UnidZip, e.FileSync.FileName, true);
                if (e.FileSync.isData)
                    Sync.upsertControlTable(0, fs.FileName, "Data", true, e.FileSync.isInSTG, e.FileSync.Cargado);

                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message);
            }
        }

        public void fs_CatStartSyncEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Sync cat automática inicia...");
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex.Message);
            }
        }//

        public void fs_CatEndSyncEvent(object sender, FolderSyncEventArgs e)
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Sync cat automática finaliza...");
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex.Message);
            }
        }//

        #endregion

        private void btn_ajustes_Click(object sender, RoutedEventArgs e)
        {
            Config.WndCnfig wndConfig = new Config.WndCnfig();
            wndConfig.Owner = this;
            wndConfig.ShowDialog();
        }

        public static void EndAppProcess(string processName)
        {
            try
            {
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.FileName = "taskkill.exe ";
                p.StartInfo.Arguments = "/F /IM " + processName;
                p.Start();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }///////////////

        public void SyncCatProcess()
        {
            FolderSync fs = new FolderSync();
            fs.CatZipPath = Configs.cnf.svrCatZipPath.ToString();
            fs.ClntCatZipPath = Configs.cnf.clntCatZipPath.ToString();
            fs.TmpCatPath = Configs.cnf.tmpCatPath.ToString();
            fs.ClientDataPath = Configs.cnf.clientDataPath.ToString();
            fs.ServerDataPath = Configs.cnf.serverDataFolder.ToString();
            fs.DataFilesFolder = Configs.cnf.dataFilesFolder.ToString();

            fs.FilesProcessedPath = Configs.cnf.ProcessedFilesSync;

            SyncThread.start(fs, (ISyncEventImp)this, true);
        }

        public void invokeRefreshUI()
        {
            this.Dispatcher.BeginInvoke(new Action(() => this.refreshUi()), null);
        }



        public void refreshUI()
        {
            try
            {
                if (this.currentControl != null)
                {
                    if (this.currentControl.GetType() == typeof(Nav3.CapturaHq))
                    {
                        if (hq != null)
                        {
                            hq.setUnidVersion(this.currentUnidVersion, this.currentTagControl);
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.CapturaFDV))
                    {
                        if (fdv != null)
                        {
                            fdv.setVersion(this.currentUnidVersion, this.currentTagControl);
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.ConsolidacionHQ))
                    {
                        if (this.chq != null)
                        {
                            this.chq.loadData(Convert.ToInt64(this.currentUnidVersion));
                        }
                    }
                    else if (this.currentControl.GetType() == typeof(Nav3.CapturaRHQ))
                    {
                        if (this.crhq != null)
                        {
                            this.loadCargaRhq();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ;
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //if (this.contentControls.Children.Count > 0)
            //{
            //    (this.contentControls.Children[0] as UserControl).Height = this.brd.ActualHeight;
            //}
        }

    }
}
